package io.gitee.hefren.hhconfig.client.conf;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Arrays;
import java.util.Optional;

/**
 * @Date 2024/5/29
 * @Author lifei
 */
public class HhConfig implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
                                        BeanDefinitionRegistry registry) {
        registerBeanDefinition(registry, HhPropertySourceProcessor.class);
        registerBeanDefinition(registry, SpringValueProcessor.class);
    }


    private void registerBeanDefinition(BeanDefinitionRegistry registry, Class<?> clazz) {
        String processorBeanName = clazz.getName();
        Optional<String> any = Arrays.stream(registry.getBeanDefinitionNames()).filter(processorBeanName::equals).findAny();
        if (any.isPresent()) {
            System.out.println("===> already register: " + processorBeanName);
            return;
        }
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
        registry.registerBeanDefinition(processorBeanName, beanDefinitionBuilder.getBeanDefinition());
    }


}
